//
//  LGPayManager.m
//  YiYuanGou
//
//  Created by 同乐 on 2017/4/25.
//  Copyright © 2017年 同乐1234521. All rights reserved.
//

#import "LGPayManager.h"
#import "LGThirdDelegate.h"

typedef void(^LGPayCallBackType)(NSError *error, NSDictionary *result);

@interface LGPayManager ()
@property (nonatomic, copy) LGPayCallBackType callBack;
@end

@implementation LGPayManager
static LGPayManager *_manager;
+ (instancetype)sharedInstance {
    if (!_manager) {
        _manager = [[LGPayManager alloc] init];
        
        [LGThirdDelegate sharedInstance].payCallback = ^(NSError *error, NSDictionary *result, LGPayType payType) {
            
            NSMutableDictionary *newResult = result.mutableCopy;
            newResult[@"appid"] = [self p_loginSDKAppId:payType];
            error ? _manager.callBack(error, nil):_manager.callBack(nil, newResult);
        };
        
    }
    
    return _manager;
}

- (void)payInWeiXin:(NSDictionary *)dic callback:(void(^)(NSError *error, NSDictionary *result))callback {
#if LGPayWeiXinIsOpen
    if (![WXApi isWXAppInstalled]) {
        NSError *noInstallError = [NSError errorWithDomain:@"com.zbsdk.pay" code:-2 userInfo:@{NSLocalizedDescriptionKey:@"您还没有安装微信客户端"}];
        callback(noInstallError, nil);
        return;
    }
    if (self.weiXinAppId.length == 0) {
        NSError *weiXinError = [NSError errorWithDomain:@"com.zbsdk.pay" code:-1 userInfo:@{NSLocalizedDescriptionKey:@"缺少参数微信appid"}];
        callback(weiXinError, nil);
        return;
    }
    _callBack = callback;
    
    
    PayReq *request = [[PayReq alloc] init];
    request.partnerId = dic[@"partnerId"];
    request.prepayId = dic[@"prepayId"];
    request.package = @"Sign=WXPay";
    request.nonceStr = dic[@"nonceStr"];
    request.timeStamp = [dic[@"timeStamp"] intValue];
    request.sign= dic[@"sign"];
    [WXApi sendReq:request];
    
#else
    NSLog(@"ZCSDK 微信支付功能暂未开发");
    
#endif
}

+ (NSString *)p_loginSDKAppId:(LGPayType)loginType {
    switch (loginType) {
        case LGPayTypeWeiXin:
            return _manager.weiXinAppId;
            break;
    }
}

@end
